package com.gbei.center.oauth.controller;

import com.gbei.center.enums.ErrorCodeEnum;
import com.gbei.center.oauth.model.AuthAccessToken;
import com.gbei.center.oauth.model.vo.UserInfo;
import com.gbei.center.oauth.service.AuthorizationService;
import com.gbei.center.oauth.service.LoginService;
import com.gbei.center.utils.JsonUtils;
import com.gbei.center.utils.message.ResponseInfo;
import com.gbei.center.utils.message.Result;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过Access Token访问的API服务
 *
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    @Resource(name = "authorizationServiceImpl")
    private AuthorizationService authorizationService;

    @Resource(name = "loginServiceImpl")
    private LoginService loginService;

    /**
     * 根据token获取用户信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/users/getInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<?> getUserInfo(HttpServletRequest request){
        String accessToken = request.getParameter("access_token");
        //查询数据库中的Access Token
        AuthAccessToken authAccessToken = authorizationService.selectByAccessToken(accessToken);
        if (authAccessToken.getGrantType().equals("authorization_code")){
            UserInfo user = loginService.userInfoByUserId(authAccessToken.getUserId());
            if (user != null){
                user.setId(insertString(insertString(user.getId(),"a",10),"c",15));
                return ResponseInfo.SUCCESS.messageToResult(user);
            }else {
                return ResponseInfo.SUCCESS_NOT_FOUND.messageToResult();
            }
        }else {
            return ResponseInfo.INVALID_TOKEN.messageToResult();
        }
    }

    /**
     * 在字符串固定的位置插入不同字符
     * a为原字符串，b为要插入的字符串，t为插入位置
     * @param a
     * @param b
     * @param t
     * @return
     */
    public String insertString(String a,String b,int t){
        return a.substring(0,t) + b + a.substring(t+1,a.length());
    }

    @RequestMapping(value = "/users/get", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getUser(HttpServletRequest request){

        String accessToken = request.getParameter("access_token");
        //查询数据库中的Access Token
        AuthAccessToken authAccessToken = authorizationService.selectByAccessToken(accessToken);

        String scope = authAccessToken.getScope();

        if (scope.contains("users")){
            UserInfo user = loginService.userInfoByUserId(authAccessToken.getUserId());
            return JsonUtils.toJson(user);
        }else {
            return this.generateErrorResponse(ErrorCodeEnum.LACK_SCOPE);
        }

    }

    @RequestMapping(value = "/product/product", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String product(HttpServletRequest request){
        String accessToken = request.getParameter("access_token");
        //查询数据库中的Access Token
        AuthAccessToken authAccessToken = authorizationService.selectByAccessToken(accessToken);

       return "product";
    }

    /**
     * 组装错误请求的返回
     */
    private String generateErrorResponse(ErrorCodeEnum errorCodeEnum) {
        Map<String,Object> result = new HashMap<>(2);
        result.put("error", errorCodeEnum.getError());
        result.put("error_description",errorCodeEnum.getErrorDescription());

        return JsonUtils.toJson(result);
    }

}
